package com.boco.pciv.core.util;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.core.entity.BizResponseUtil;
import com.boco.pciv.core.exception.AuthFailException;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.exception.TokenAuthExpiredException;
import com.boco.pciv.core.exception.TokenAuthFailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by CC on 2017/9/26.
 */
public class RequestUtil {

    //logger
    private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);
    /**
     * 将map转换成url
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        s = StrUtil.removeSuffix(s,"&");
        return s;
    }
    /**
     * 将url参数转换成map
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    public static  Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        if (StrUtil.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    public static String getClientIp(HttpServletRequest request){
        String xip = request.getHeader("X-Forwarded-For");
        if (StrUtil.isNotBlank(xip)){
            return xip;
        } else{
            return request.getRemoteAddr();
        }

    }
    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        renderJson(response,jsonObject,200);
    }
    public static void renderJson(HttpServletResponse response, Object jsonObject, Integer HttpStatusCode) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatusCode);
            PrintWriter writer = response.getWriter();
            writer.write(JsonUtil.toJsonStr(jsonObject));
        } catch (IOException ex) {
            logger.warn("renderJson失败",ex);
        }
    }
    public static void renderException(HttpServletResponse response, PcivException exp) {
        int code =500;
        if (exp instanceof AuthFailException || exp instanceof TokenAuthFailException ||
                exp instanceof TokenAuthExpiredException){
            code= HttpStatus.UNAUTHORIZED.value();
        } else {
            code= HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        renderJson(response, BizResponseUtil.error(exp),code);
    }
}
